﻿#include "widget.h"
#include <QVBoxLayout>
#include <QDebug>
#include <iostream>
#include <fstream>
#include <QFile>
#include <QDateTime>

//组合文件功能函数
void concatenate_binary_files(const std::string& output_file, const std::vector<std::string>& input_files)
{
    std::ofstream out(output_file, std::ios::binary);
    if (!out)
    {
        std::cerr << "无法打开输出文件： " << output_file << std::endl;
        return;
    }
    for (const auto& input_file : input_files)
    {
        std::ifstream in(input_file, std::ios::binary);
        if (!in)
        {
            std::cerr << "无法打开输入文件： " << input_file << std::endl;
            continue;
        }

        out << in.rdbuf();
        in.close();
    }
    out.close();
}


Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    setWindowTitle(QString::fromUtf16(u"文件拼接小工具"));
    AppInit();
    setAcceptDrops(true);
}

Widget::~Widget()
{

}

void Widget::AppInit()
{
    QVBoxLayout *vlay = new QVBoxLayout;
    QHBoxLayout *hlay = new QHBoxLayout;

    m_pListWidget = new QListWidget;
    m_pBtnMontage = new QPushButton(QString::fromUtf16(u"拼接"));
    QSpacerItem *spacer = new QSpacerItem(40, 20, QSizePolicy::Expanding);


    hlay->addItem(spacer);
    hlay->addWidget(m_pBtnMontage);

    vlay->addWidget(m_pListWidget);
    vlay->addLayout(hlay);

    this->setLayout(vlay);

    connect(m_pBtnMontage, SIGNAL(clicked()), this, SLOT(slot_Montage()));
    resize(500, 300);
}

void Widget::slot_Montage()
{
    if(m_pListWidget->count() < 1)
    {
        qDebug()<<QString::fromUtf16(u"没有添加拖拽文件");
        return;
    }

    QString str = QString::number(QDateTime::currentMSecsSinceEpoch());
    std::string output_file = str.toStdString() + "-Montage.raw";

    std::vector<std::string> input_files;
    for(int i = 0; i < m_pListWidget->count(); i++)
    {
        input_files.push_back(m_pListWidget->item(i)->text().toStdString());
    }
    concatenate_binary_files(output_file, input_files);

    qDebug()<<QString::fromUtf16(u"文件拼接完成，输出文件为： ")<<QString::fromStdString(output_file);
}

void Widget::dragEnterEvent(QDragEnterEvent *event)
{
    if(event->mimeData()->hasUrls())
    {
        event->acceptProposedAction();
    }
    else
    {
        event->ignore();
    }
}

void Widget::dropEvent(QDropEvent *event)
{
    m_pListWidget->clear();
    const QMimeData* mimeDate = event->mimeData();
    if(mimeDate->hasUrls())
    {
        QList<QUrl> urlList = mimeDate->urls();
        for (int i = 0; i < urlList.size(); i++)
        {
            m_pListWidget->addItem(urlList.at(i).toLocalFile());
        }
    }
}
